<?php
/**
 * Created by PhpStorm.
 * User: 吴锋
 * Date: 2017/12/5
 * Time: 13:54
 */
namespace app\admin\service;

use app\models\AuthGroupModel;

class AuthGroupService
{
    /**
     * 用户组列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $page = input('page',1);
        $listRows = input('limit',15);
        $firstRow=($page-1)*$listRows;
        $groupModel = new AuthGroupModel();
        //查询用户组的所有数据分页渲染
        $groups = $groupModel
            ->where('type',input('type','1'))
            ->order('id desc')
            ->limit($firstRow.',',$listRows)
            ->select();
        $count= $groupModel
            ->where('type',input('type','1'))
            ->count();
        foreach ($groups as &$group) {
            //通过传值status获取状态
            $group['status_text'] = $group['status'];
        }
        return ['code' => 0, 'msg' => "ok", 'data' => $groups, 'count' => $count];
    }

    /**
     * 添加用户组
     * @return array
     * @throws \think\exception\DbException
     */
    public function add()
    {
        $data = input();
        $groupModel = new AuthGroupModel();
        /*校验：是否重复提交*/
        $check = $groupModel::get(['title' => $data['title']]);
        if ($check) {
            return ['code'=>1,'msg'=>"用户组已存在"];
        }
        $group = $groupModel::create($data)->save();
        if($group !== false){
            return ['code'=>0,'msg'=>"添加成功"];
        }
        return ['code'=>1,'msg'=>"添加失败"];
    }

    /**
     * 修改用户组
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $data = input('post.');
        $groupModel = new AuthGroupModel();
        /*校验：是否重复提交*/
        $check = $groupModel::where('title',$data['title'])->find();
        if ($check) {
            if($check['id'] != $data['id']){
                return ['code'=>1,'msg'=>"用户组已存在"];
            }
        }
        $group = $groupModel::update($data);
        if($group !== false){
            return ['code'=>0,'msg'=>"修改成功"];
        }
        return ['code'=>1,'msg'=>"修改失败"];

    }

    /**
     * 分配权限
     * @return array
     */
    public function rule_group()
    {
        $data = input('post.');
        $rule_ids = implode(",", $data['menu']);
        $role_id = $data['id'];
        if(!count($rule_ids)){
            return ['code' => 1, 'msg' => "请选择需要分配的权限"];
        }
        $groupModel = new AuthGroupModel();
        if($groupModel->addAuthRule($rule_ids, $role_id) !== false){
            return ['code' => 0, 'msg' => "分配成功"];
        }
        return ['code' => 1, 'msg' => "分配失败"];
    }
}